﻿using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using Nuclear.Models.DtoModels;
using Nuclear.Services;
using Nuclear.Validations;
using static Nuclear.Models.DtoModels.Errors;

namespace Nuclear.Controllers;

[ApiController]
[Route("api/merchant")]
public class MerchantController(
    IDbService db,
    ILogger<MerchantController> logger) : ControllerBase
{
    [HttpPost("login")]
    public async Task<MerchantLoginResponseDto> LoginAsync(
        [FromQuery(Name = "api_key")] string apiKey,
        [FromBody] MerchantLoginRequestDto request,
        [FromServices] IValidator<MerchantLoginRequestDto> validator,
        CancellationToken token = default)
    {
        logger.LogInformation("Merchant logging in");
        var result =
            await validator
                .ValidateRequestAsync<MerchantLoginRequestDto, MerchantLoginResponseDto>(apiKey, request, token);

        if (result is not null)
            return result;

        var system = await db.GetSoftwareSystemAsync(request.SystemId, token);
        if (system is null)
            return InvalidSystemId<MerchantLoginResponseDto>(request.SystemId);

        switch (system.Id)
        {
            case SystemIds.GiftPiker:
                var systemAdmin = await db.LoginAsCrmebMerchantAsync(request.UserName, request.Password, token);
                return systemAdmin is null 
                    ? UserNameOrPasswordIncorrect<MerchantLoginResponseDto>() 
                    : new MerchantLoginResponseDto(systemAdmin.MerchantId.ToString(), systemAdmin.RealName);

            default:
                return SystemLoginNotSupported<MerchantLoginResponseDto>(system.Id);
        }
        
    }
}